from flask import Flask, request, jsonify
from flask_jwt_extended import verify_jwt_in_request

from exts import db, mail, jwt, redis
from flask_migrate import Migrate
import config
from router.article_router import article_bp
from router.category_router import category_bp
from router.user_router import user_bp
from utils import response

app = Flask(__name__)
app.config.from_object(config)

app.logger.disabled = True  # 禁用 Flask 默认日志
# logging.getLogger('werkzeug').disabled = True  # 禁用 Werkzeug 日志
app.logger.handlers.clear()

# 蓝图
app.register_blueprint(category_bp)
app.register_blueprint(user_bp)
app.register_blueprint(article_bp)

db.init_app(app)
mail.init_app(app)
jwt.init_app(app)

migrate = Migrate(app, db)


@app.before_request
def before_request():
    # 排除登录路由
    green_list = ['/user/login','/user/register']
    if request.path in green_list :
        return

    # 检查是否需要验证 Token
    if request.method != 'OPTIONS':  # 排除预检请求
        try:
            verify_jwt_in_request()  # 验证 Token
        except:
            return response(401, "Token 不正确", None)

        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return response(401, "Token 头部格式异常", None)

        token = auth_header.split(" ")[1]
        if not redis.get(token):
            return response(401,"Token 已失效", None)


if __name__ == '__main__':
    app.run(debug=True)
